package com.gs.wechatdemo.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.google.gson.reflect.TypeToken;
import com.gs.wechatdemo.MyApplication;
import com.gs.wechatdemo.R;
import com.gs.wechatdemo.activity.ChatListActivity;
import com.gs.wechatdemo.constant.AllConstants;
import com.gs.wechatdemo.constant.ImageEditCode;
import com.gs.wechatdemo.db.bean.ContactBean;
import com.gs.wechatdemo.db.dto.EventBean;
import com.gs.wechatdemo.db.dto.MsgContentDto;
import com.gs.wechatdemo.db.dto.MsgDto;
import com.gs.wechatdemo.db.sqlite.SQLiteUtil;
import com.gs.wechatdemo.receiver.NotificationReceiver;
import com.gs.wechatdemo.signalr.SignalRCode;
import com.gs.wechatdemo.signalr.SignalRUtil;
import com.gs.wechatdemo.util.GsonUtil;
import com.gs.wechatdemo.util.NotificationUtil;
import com.gs.wechatdemo.util.SPUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;

public class SignalRService extends Service {
    private int i = 0;
    private PowerManager.WakeLock wakeLock;
    private ActivityManager am;
    private String myId;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SignalRCode.RECEIVE_NUM:
                    Bundle bundle = msg.getData();
                    if (bundle == null) return;
                    String msgType = bundle.getString(AllConstants.MSG_TYPE);
                    String msgJson = bundle.getString(AllConstants.MSG);
                    if (TextUtils.isEmpty(msgType) || TextUtils.isEmpty(msgJson)) return;
                    // 收到消息
                    if (msgType.equals(SignalRCode.TYPE_USER)
                            || msgType.equals(SignalRCode.TYPE_LOGIN)
                            || msgType.equals(SignalRCode.TYPE_LOGOUT)) {
                        EventBus.getDefault().post(new EventBean(msgType, msgJson, false));
                        return;
                    }
                    // 应用处于后台，显示通知
                    if (!MyApplication.isFront()) {
                        MsgDto<MsgContentDto> msgDto = (MsgDto<MsgContentDto>) GsonUtil.getInstance().fromJson(msgJson, new TypeToken<MsgDto<MsgContentDto>>() {
                        }.getType());
                        photoToBitmap(msgDto.getMsg().getFromId(), msgDto.getMsg().getToId(), msgDto);
                    }
                    if (MyApplication.getCurrentAct() instanceof ChatListActivity) {
                        MsgDto<MsgContentDto> msgDto = (MsgDto<MsgContentDto>) GsonUtil.getInstance().fromJson(msgJson, new TypeToken<MsgDto<MsgContentDto>>() {
                        }.getType());
                        String fromId = msgDto.getMsg().getFromId();
                        String otherId = SPUtil.getInstance().getString(AllConstants.OTHER_ID);
                        String toId = msgDto.getMsg().getToId();
                        // 当前聊天界面对方id是否与收到的消息id相等
                        if (myId.equals(toId) && otherId.equalsIgnoreCase(fromId)) {
                            EventBus.getDefault().post(new EventBean(msgType, msgJson, false));
                            return;
                        }
                        if (otherId.equalsIgnoreCase(toId)) {
                            EventBus.getDefault().post(new EventBean(msgType, msgJson, false));
                            return;
                        }
                        if (MyApplication.isFront()) {
                            photoToBitmap(fromId, toId, msgDto);
                        }
                    }
                    EventBus.getDefault().post(new EventBean(msgType, msgJson, true));
                    break;
                case SignalRCode.RESULT_NUM:
                    break;
//                case ImageEditCode.EDIT_MSG:
//                    Bitmap bitmap = (Bitmap) msg.obj;
//                    showNotification(msgDto, bitmap);
//                    break;
            }
        }
    };

    /**
     * 获取消息user的头像，转为bitmap
     *
     * @param fromId
     * @param toId
     * @param msgDto
     */
    private void photoToBitmap(String fromId, String toId, MsgDto<MsgContentDto> msgDto) {
        String content = "";
        switch (msgDto.getMsgType()) {
            case SignalRCode.TYPE_USER_WORD:
            case SignalRCode.TYPE_GROUP_WORD:
                content = msgDto.getMsg().getContent();
                break;
            case SignalRCode.TYPE_USER_IMG:
            case SignalRCode.TYPE_GROUP_IMG:
                content = "图片";
                break;
            case SignalRCode.TYPE_USER_VOICE:
            case SignalRCode.TYPE_GROUP_VOICE:
                content = "语音";
                break;
        }
        String id;
        if (toId.equalsIgnoreCase(myId)) {
            id = fromId;
        } else {
            ContactBean bean = SQLiteUtil.getInstance().queryContactById(fromId);
            content = bean.getName()+"："+content;
            id = toId;
        }
        ContactBean bean = SQLiteUtil.getInstance().queryContactById(id);
        showNotification(id, bean.getName(), content);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(AllConstants.TAG, "service onStartCommand");
        myId = SPUtil.getInstance().getString(AllConstants.ID);
        SignalRUtil.getInstance().startConnect(handler);
        if (am == null) {
            am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        }
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "demo:CPUKeepRunning");
            wakeLock.setReferenceCounted(true);
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            int hour = c.get(Calendar.HOUR_OF_DAY);
            if (hour >= 23 || hour <= 6) {
                wakeLock.acquire(5000);
            } else {
                wakeLock.acquire(300000);
            }
        }
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onDestroy() {
        if (wakeLock != null) {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                wakeLock = null;
            }
        }
        SignalRUtil.getInstance().stopConnect();
        Log.i(AllConstants.TAG, "service onDestroy");
        super.onDestroy();
    }

    private void showNotification(String id, String name, String content) {
        i++;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtil.getInstance().getNotificationManager().createNotificationChannel(NotificationUtil.getInstance().getChannel(true));
            Notification.Builder builder = NotificationUtil.getInstance().getNotification(this, true)
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentIntent(createIntent(i, id))
                    .setCustomContentView(getNotificationView(name, content));
            NotificationUtil.getInstance().getNotificationManager().notify(i, builder.build());
        } else {
            NotificationCompat.Builder builder = NotificationUtil.getInstance().getNotificationCompat(this, true)
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentIntent(createIntent(i, id))
                    .setCustomContentView(getNotificationView(name, content));
            NotificationUtil.getInstance().getNotificationManager().notify(i, builder.build());
        }
    }

    /**
     * 获取自定义的通知
     *
     * @return
     */
    private RemoteViews getNotificationView(String name, String content) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_msg);
        setTextViewText(remoteViews, name, content);
        return remoteViews;
    }

    private void setTextViewText(RemoteViews remoteViews, String name, String content) {
        remoteViews.setTextViewText(R.id.tv_name, name);
        remoteViews.setTextViewText(R.id.tv_content, content);
    }


    /**
     * 发送广播
     *
     * @return
     */
    private PendingIntent createIntent(int num, String id) {
        Intent intent = new Intent(this, NotificationReceiver.class);
        intent.putExtra(AllConstants.OTHER_ID, id);
        return PendingIntent.getBroadcast(this, num, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }
}
